<template>
  <div class="event-container">
    <!-- 头部导航 -->
    <el-header class="header">
      <div class="header-content">
        <h1>活动中心</h1>
        <div class="actions">
          <el-button type="primary" @click="showUploadDialog = true" round>
            <el-icon><Plus /></el-icon> 发布新活动
          </el-button>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索活动..."
            clearable
            style="width: 300px; margin-left: 20px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </el-header>

    <!-- 活动列表 -->
    <el-main class="main-content">
      <div class="sort-controls">
        <el-radio-group v-model="sortType" @change="loadEvents">
          <el-radio-button label="time">最新活动</el-radio-button>
          <el-radio-button label="likes">最受欢迎</el-radio-button>
        </el-radio-group>
      </div>

      <el-skeleton :rows="6" animated :loading="loading">
        <template #default>
          <transition-group name="list" tag="div">
            <el-card
              v-for="event in sortedEvents"
              :key="event.event_id"
              class="event-card"
              :class="{ 'is-top': event.is_top }"
            >
              <template #header>
                <div class="card-header">
                  <div class="title-container">
                    <el-tag v-if="event.is_top" type="danger" effect="dark"
                      >置顶</el-tag
                    >
                    <h3>{{ event.title }}</h3>
                  </div>
                  <div class="header-actions">
                    <el-button
                      v-if="currentUserId === event.user_id"
                      type="danger"
                      circle
                      @click="handleDelete(event.event_id)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </template>

              <div class="event-content">
                <p class="description">{{ event.description }}</p>
                <div class="meta-info">
                  <div class="info-item">
                    <el-icon><User /></el-icon>
                    <span>发起人：用户{{ event.user_id }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ event.location }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ formatDate(event.event_date) }}</span>
                  </div>
                </div>
              </div>

              <div class="card-footer">
                <el-button
                  :type="event.liked ? 'danger' : 'primary'"
                  :disabled="event.liked"
                  @click="handleLike(event)"
                >
                  <el-icon><Star /></el-icon>
                  {{ event.likes }} 点赞
                </el-button>
              </div>
            </el-card>
          </transition-group>
        </template>
      </el-skeleton>
    </el-main>

    <!-- 发布活动对话框 -->
    <el-dialog v-model="showUploadDialog" title="发布新活动">
      <el-form :model="newEvent" label-width="80px">
        <el-form-item label="标题" required>
          <el-input v-model="newEvent.title" />
        </el-form-item>
        <el-form-item label="描述" required>
          <el-input v-model="newEvent.description" type="textarea" rows="4" />
        </el-form-item>
        <el-form-item label="地点" required>
          <el-input v-model="newEvent.location" />
        </el-form-item>
        <el-form-item label="时间" required>
          <el-date-picker
            v-model="newEvent.event_date"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpload">发布</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Plus,
  Search,
  Star,
  User,
  Location,
  Clock,
} from "@element-plus/icons-vue";

export default {
  components: {
    Delete,
    Plus,
    Search,
    Star,
    User,
    Location,
    Clock,
  },
  data() {
    return {
      loading: true,
      sortType: "time",
      searchKeyword: "",
      showUploadDialog: false,
      events: [],
      newEvent: {
        title: "",
        description: "",
        location: "",
        event_date: "",
      },
    };
  },
  computed: {
    currentUserId() {
      return this.$store.state.user_id;
    },
    sortedEvents() {
      return [...this.events].sort((a, b) => {
        if (a.is_top !== b.is_top) return b.is_top - a.is_top;
        if (this.sortType === "likes") return b.likes - a.likes;
        return new Date(b.event_date) - new Date(a.event_date);
      });
    },
  },
  mounted() {
    this.checkAuth();
    this.loadEvents();
  },
  methods: {
    checkAuth() {
      if (!this.currentUserId) {
        this.$router.push("/user/login");
        ElMessage.error("登录状态失效，请重新登录！");
      }
    },

    formatDate(dateString) {
      return new Date(dateString).toLocaleString();
    },

    async loadEvents() {
      try {
        this.loading = true;
        const response = await axios.get(`/events?sort=${this.sortType}`);
        this.events = response.data;
      } catch (error) {
        ElMessage.error("加载活动失败");
      } finally {
        this.loading = false;
      }
    },

    async handleSearch() {
      try {
        const response = await axios.get("/events/search?sort=time", {
          params: { keyword: this.searchKeyword },
        });
        this.events = response.data;
      } catch (error) {
        ElMessage.error("搜索失败");
      }
    },

    async handleUpload() {
      try {
        const formData = new FormData();
        formData.append("user_id", this.currentUserId);
        formData.append("title", this.newEvent.title);
        formData.append("description", this.newEvent.description);
        formData.append("location", this.newEvent.location);
        formData.append("event_date", this.newEvent.event_date);

        await axios.post("/events/upload", formData);

        this.events.unshift({
          ...this.newEvent,
          event_id: Date.now(),
          user_id: this.currentUserId,
          likes: 0,
          is_top: false,
          liked: false,
        });

        ElMessage.success("活动发布成功");
        this.showUploadDialog = false;
        this.resetForm();
      } catch (error) {
        ElMessage.error("发布失败");
      }
    },

    resetForm() {
      this.newEvent = {
        title: "",
        description: "",
        location: "",
        event_date: "",
      };
    },

    async handleLike(event) {
      if (!this.currentUserId) {
        this.$router.push("/user/login");
        return;
      }

      try {
        const formData = new FormData();
        formData.append("user_id", this.currentUserId);

        await axios.post(`/events/${event.event_id}/like`, formData);
        event.likes++;
        event.liked = true;
        ElMessage.success("点赞成功");
      } catch (error) {
        ElMessage.error("点赞失败");
      }
    },

    async handleDelete(eventId) {
      try {
        await ElMessageBox.confirm("确定要删除该活动吗？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        await axios.delete(`/events/${eventId}`);
        this.events = this.events.filter((e) => e.event_id !== eventId);
        ElMessage.success("删除成功");
      } catch (error) {
        // 取消删除时不处理
      }
    },
  },
};
</script>

<style scoped>
.event-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.header {
  background: linear-gradient(135deg, #409eff, #79bbff);
  color: white;
  margin-bottom: 20px;
  border-radius: 8px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.sort-controls {
  margin-bottom: 20px;
}

.event-card {
  border-left: 4px solid #b4dfff;
  background: #effaff;
  margin-bottom: 20px;
  transition: all 0.3s;
}

.event-card.is-top {
  border-left: 4px solid #e6a23c;
  background: #fff9ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.event-content {
  padding: 10px 0;
}

.meta-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
  color: #666;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.card-footer {
  margin-top: 15px;
  text-align: right;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 移动端优化 */
@media (max-width: 480px) {
  /* 容器调整 */
  .event-container {
    padding: 10px;
  }

  /* 标题和头部样式调整 */
  .header {
    margin-bottom: 20px;
    text-align: center; /* 让活动中心标题居中 */
    display: flex;
    justify-content: center; /* 居中 */
    align-items: center; /* 垂直居中 */
    height: 40px; /* 适当的高度 */
  }

  .header-content h1 {
    font-size: 1.5rem;
    margin: 0;
  }

  /* 使用Flexbox让标题、按钮、输入框排列 */
  .header-content {
    display: flex;
    flex-direction: column; /* 垂直堆叠 */
    align-items: center; /* 居中对齐 */
    gap: 15px; /* 设置元素之间的间距 */
  }

  /* 选项卡下移 */
  .sort-controls {
    display: flex;
    flex-direction: column; /* 垂直堆叠 */
    align-items: center; /* 居中对齐 */
    width: 100%;
    margin-top: 45px; /* 强制下移选项卡 */
  }

  /* 搜索框样式 */
  .el-input {
    width: 100%; /* 让搜索框占满父容器 */
    font-size: 14px; /* 调整字体大小 */
    margin-bottom: 20px; /* 增加底部间距 */
  }

  /* 发布新活动按钮 */
  .el-button {
    width: 100%; /* 让按钮占满父容器 */
    font-size: 14px; /* 调整字体大小 */
    margin-bottom: 10px; /* 增加底部间距 */
  }

  /* 活动中心文字和按钮之间的间距调整 */
  .header-content > .el-button,
  .header-content > .el-input {
    margin-bottom: 10px; /* 每个元素底部增加间距，避免重叠 */
  }

  /* 调整卡片的间距 */
  .event-card {
    margin-bottom: 15px;
    padding: 10px;
    margin-top: 10px; /* 下移帖子卡片 */
  }

  /* 卡片内的信息内容 */
  .meta-info {
    display: block; /* 让meta信息垂直排列 */
    margin-top: 10px;
  }

  .info-item {
    margin-bottom: 10px; /* 增加信息项之间的间距 */
  }

  /* 按钮的文本大小和宽度 */
  .el-button {
    font-size: 14px;
    width: 100%; /* 让按钮在手机端宽度适应屏幕 */
  }
}
</style>